package bjx.com.kehu.ui.activity;

import android.app.AlertDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.LogoPosition;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapViewLayoutParams;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.bumptech.glide.Glide;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushManager;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.service.DownloadService;
import com.vector.update_app.utils.AppUpdateUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import bjx.com.kehu.R;
import bjx.com.kehu.adapter.MainViewPagerAdapter;
import bjx.com.kehu.application.App;
import bjx.com.kehu.contants.Constants;
import bjx.com.kehu.model.DriverModel;
import bjx.com.kehu.service.LocationService;
import bjx.com.kehu.ui.http.OkGoUpdateHttpUtil;
import bjx.com.kehu.utils.CProgressDialogUtils;
import bjx.com.kehu.utils.DateUtils;
import bjx.com.kehu.utils.GsonUtil;
import bjx.com.kehu.utils.HProgressDialogUtils;
import bjx.com.kehu.utils.LogsUtil;
import bjx.com.kehu.utils.MD5;
import bjx.com.kehu.utils.PermissionUtils;
import bjx.com.kehu.utils.SPUtils;
import bjx.com.kehu.utils.ToastUtil;
import bjx.com.kehu.utils.Util;
import bjx.com.kehu.view.NoScrollViewPager;
import bjx.com.kehu.view.WhewView;
import bjx.com.kehu.widget.CustomDatePicker;
import bjx.com.kehu.widget.DriverCountPopWin;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by jqc on 2017/10/19.
 */

/**
 * @author wang
 * @time 2018/10/28 11:24
 * @method
 */

public class MainActivity extends BaseActivity {

    // 侧边栏区域
    ImageView mIVNavigation;
    DrawerLayout mDrawer;
    ImageView mIVHead;
    TextView mTVNickName;
    TextView mTVTel;
    TextView mTVVipType;
    LinearLayout mLLMyOrder;
    LinearLayout mLLAccount;
    LinearLayout mLLMsg;
    LinearLayout mLLMyAdvise;
    LinearLayout mLLSetting;
    LinearLayout mLLLuckDraw;
    LinearLayout mLLPartner;
    LinearLayout mLLEnroll;
    TextView mTVLogout;

    TextureMapView mMapView;
    BaiduMap mBaiduMap;
    LocationService locationService;
    MyLocationData locData;
    BitmapDescriptor mCurrentMarker; // 当前定位点


    boolean isFirstLoc = true; // 是否首次定位
    boolean isPushOrder = false; // 是否派单中
    double mCurrentLat;  // 用户当前坐标
    double mCurrentLon;
    String mCurrentLocName; // 用户当前位置名称
    double mStartLat;  // 用户出发地坐标
    double mStartLon;
    String mStartLocName; // 出发地名称
    double mEndLat;  // 用户目的地坐标
    double mEndLon;
    String mEndLocName; // 目的地名称
    String mOrderType = "1"; // 当前订单类型
    String mDriverCount = "1";
    float mCurrentAccracy;
    int paddingBottom; // 地图paddingbottom
    List<PoiInfo> mCurrentPoiList;
    GeoCoder mGeoSearch;
    RoutePlanSearch mRoutePlanSearch;


    RelativeLayout mRLTip; // 用户提示区域
    TextView mTVTipDistance; // 司机用户距离信息
    TextView mTVTipMsg; // 提示消息
    ImageView mIVPosition; // 手动定位
    LinearLayout mLLWay; // 下单方式
    TextView mTVDaily; // 日常
    TextView mTVYuYue; // 预约
    TextView mTVChangTu; // 长途

    NoScrollViewPager mVPMain;
    MainViewPagerAdapter mainViewPagerAdapter;
    View mViewDaily; // 日常区域
    TextView mTVDailyStartLoc;
    TextView mTVDailyEndLoc;
    TextView mTVDailyOneOrder;
    TextView mTVDailyDCall;

    View mViewYuyue; // 预约区域
    LinearLayout mLLYuYueStartTime; // 预约-出发时间区域
    TextView mTVYuYueStartTime; // 预约-出发时间
    TextView mTVYuYueStartLoc; // 预约-出发地
    TextView mTVYuYueEndLoc; // 预约-目的地

    View mViewChangtu;  // 长途区域
    LinearLayout mLLChangTuStartTime; // 长途-出发时间区域
    TextView mTVChangTuStartTime; // 长途-出发时间
    TextView mTVChangTuStartLoc; // 长途-出发地
    TextView mTVChangTuEndLoc; // 长途-目的地

    RelativeLayout mRLOrder; // 下单toolbar
    TextView mTVOrderTitle; // 下单标题
    ImageView mIVOrderBack; // 下单返回
    LinearLayout mLLForm; // 下单表单
    LinearLayout mLLDCount; // 司机数量区域
    LinearLayout mLLStartTime; // 出发时间区域
    TextView mTVStartLoc; // 出发地
    TextView mTVEndLoc; // 目的地
    LinearLayout mLLMPerson; // 修改联系人区域
    LinearLayout mLLRemark; // 备注区域
    LinearLayout mLLGuJia; // 估价区域
    TextView mTVOrder; // 下单按钮

    TextView mTVDCount; // 司机数量
    TextView mTVStartTime; // 出发时间
    TextView mTVMPerson; // 联系人
    TextView mTVPayType; // 支付方式
    TextView mTVRemark; // 备注
    TextView mTVRemarkStr;
    TextView mTVGuJia; // 估价

    RelativeLayout mRLPushOrder; // 派单toolbar
    TextView mTVPushOrderCancel; // 取消派单
    ImageView mIVPushOrderBack; // 派单返回
    TextView mTVPushOrderTitle; // 派单标题

    RelativeLayout mRLAcceptOrder; // 司机接单区域
    TextView mTVDriverName; // 接单司机名称
    ImageView mIVDriverHead; // 接单司机头像
    ImageView mIVDriverTel; // 接单司机电话

    TextView refresh_driver; // 手动获取司机位置

    String mCurOrderList;

    WhewView wv;
    TextView LocationResult; // 测试
    List<DriverModel> mDriverList = new ArrayList<>();

    CustomDatePicker mCDPYuYue, mCDPChangtu, mCDPOrder;
    DriverCountPopWin mDriverCountPopWin; // 司机数量弹出窗

    private String currentOrderId;
    private ReverseGeoCodeResult mCurGeoCodeResult;

    private boolean isShowDownloadProgress;

    private String mUpdateUrl = "http://swdj.ejiuyuan.com/index.php/Api/Api/update_kehu??";

    final int REQUEST_CODE_CONTACT = 101;

    public void logMsg(String str) {
        final String s = str;
        try {
            if (LocationResult != null) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        LocationResult.post(new Runnable() {
                            @Override
                            public void run() {
                                LocationResult.setText(s);
                            }
                        });

                    }
                }).start();
            }
            //LocationResult.setText(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new PermissionUtils(this).requestLocationSDPermissions(200);
        }

        // 侧边栏区域控件
        mIVNavigation = getViewById(R.id.navigation);
        mDrawer = getViewById(R.id.drawer_layout);
        mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        mIVHead = getViewById(R.id.drawer_iv_head);
        mTVNickName = getViewById(R.id.drawer_tv_nickname);
        mTVTel = getViewById(R.id.drawer_tv_tel);
        Drawable drawable = getResources().getDrawable(R.mipmap.tel);
        drawable.setBounds(0, 0, Util.dip2px(mApp, 15), Util.dip2px(mApp, 15));
        mTVTel.setCompoundDrawables(drawable, null, null, null);
        mTVVipType = getViewById(R.id.drawer_tv_viptype);
        mLLMyOrder = getViewById(R.id.drawer_ll_myorder);
        mLLAccount = getViewById(R.id.drawer_ll_myaccount);
        mLLMsg = getViewById(R.id.drawer_ll_mymsg);
        mLLMyAdvise = getViewById(R.id.drawer_ll_myadvise);
        mLLSetting = getViewById(R.id.drawer_ll_setting);
        mLLLuckDraw = getViewById(R.id.drawer_ll_luckdraw);
        mLLPartner = getViewById(R.id.drawer_ll_partner);
        mLLEnroll = getViewById(R.id.drawer_ll_enroll);
        mTVLogout = getViewById(R.id.drawer_tv_logout);

        //获取地图控件引用
        mMapView = getViewById(R.id.bmapView);
        mMapView.showZoomControls(false);
        mMapView.showScaleControl(false);
        mMapView.setLogoPosition(LogoPosition.logoPostionRightBottom);
        mBaiduMap = mMapView.getMap();
        mCurrentMarker = BitmapDescriptorFactory.fromResource(R.mipmap.icon_geo); // 设置自定义定位点
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker));
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                setPadding(180); // 设置padding
                addView(mMapView);
            }
        });
        mBaiduMap.setOnMapStatusChangeListener(onMapStatusChangeListener); // 监听地图状态
        mRLTip = getViewById(R.id.main_rl_tip);
        mTVTipDistance = getViewById(R.id.main_tv_tip_distance);
        mTVTipMsg = getViewById(R.id.main_tv_tip_msg);
        mIVPosition = getViewById(R.id.main_iv_position);
        mLLWay = getViewById(R.id.main_ll_way);
        mTVDaily = getViewById(R.id.main_tv_way_daily);
        mTVYuYue = getViewById(R.id.main_tv_way_yuyue);
        mTVChangTu = getViewById(R.id.main_tv_way_changtu);

        // 选单界面
        mViewDaily = LayoutInflater.from(mApp).inflate(R.layout.view_daily, null);
        mTVDailyStartLoc = (TextView) mViewDaily.findViewById(R.id.daily_tv_startLoc);
        mTVDailyEndLoc = (TextView) mViewDaily.findViewById(R.id.daily_tv_endLoc);
        mTVDailyOneOrder = (TextView) mViewDaily.findViewById(R.id.daily_tv_oneorder);
        mTVDailyDCall = (TextView) mViewDaily.findViewById(R.id.daily_tv_dcall);

        mViewYuyue = LayoutInflater.from(mApp).inflate(R.layout.view_yuyue, null);
        mLLYuYueStartTime = (LinearLayout) mViewYuyue.findViewById(R.id.yuyue_ll_startTime);
        mTVYuYueStartTime = (TextView) mViewYuyue.findViewById(R.id.yuyue_tv_startTime);
        mTVYuYueStartLoc = (TextView) mViewYuyue.findViewById(R.id.yuyue_tv_startLoc);
        mTVYuYueEndLoc = (TextView) mViewYuyue.findViewById(R.id.yuyue_tv_endLoc);

        mViewChangtu = LayoutInflater.from(mApp).inflate(R.layout.view_changtu, null);
        mLLChangTuStartTime = (LinearLayout) mViewChangtu.findViewById(R.id.changtu_ll_startTime);
        mTVChangTuStartTime = (TextView) mViewChangtu.findViewById(R.id.changtu_tv_startTime);
        mTVChangTuStartLoc = (TextView) mViewChangtu.findViewById(R.id.changtu_tv_startLoc);
        mTVChangTuEndLoc = (TextView) mViewChangtu.findViewById(R.id.changtu_tv_endLoc);

        mVPMain = getViewById(R.id.main_vp_main);
        List<View> list_view = new ArrayList<>();
        list_view.add(mViewDaily);
        list_view.add(mViewYuyue);
        list_view.add(mViewChangtu);
        mainViewPagerAdapter = new MainViewPagerAdapter(mApp, list_view);
        mVPMain.setAdapter(mainViewPagerAdapter);
        mVPMain.setNoScroll(true);


        // 下单界面
        mRLOrder = getViewById(R.id.order_toolbar); // 下单toolbar
        mTVOrderTitle = getViewById(R.id.order_title); // 下单标题
        mIVOrderBack = getViewById(R.id.order_back); // 下单返回
        mLLForm = getViewById(R.id.main_ll_form);
        mLLDCount = getViewById(R.id.main_ll_dCount); // 司机数量区域
        mLLStartTime = getViewById(R.id.main_ll_startTime); // 出发时间区域
        mTVStartLoc = getViewById(R.id.main_tv_startLoc); // 出发地
        mTVEndLoc = getViewById(R.id.main_tv_endLoc); // 目的地
        mLLMPerson = getViewById(R.id.main_ll_mperson); // 修改联系人区域
        mLLRemark = getViewById(R.id.main_ll_remark); // 备注区域
        mLLGuJia = getViewById(R.id.main_ll_gujia); // 估价区域
        mTVOrder = getViewById(R.id.main_tv_oneorder); // 下单按钮

        mTVDCount = getViewById(R.id.main_tv_dCount); // 司机数量
        mTVStartTime = getViewById(R.id.main_tv_startTime); // 出发时间
        mTVMPerson = getViewById(R.id.main_tv_mperson); // 联系人
        Drawable mMPersonDrawable = getResources().getDrawable(R.mipmap.user);
        mMPersonDrawable.setBounds(0, 0, Util.dip2px(mApp, 20), Util.dip2px(mApp, 20));
        mTVMPerson.setCompoundDrawables(mMPersonDrawable, null, null, null);
        mTVPayType = getViewById(R.id.main_tv_paytype); // 支付方式
        mTVRemark = getViewById(R.id.main_tv_remark); // 备注
        mTVRemarkStr = getViewById(R.id.main_tv_remarkstr);
        Drawable mRemarkDrawable = getResources().getDrawable(R.mipmap.remark);
        mRemarkDrawable.setBounds(0, 0, Util.dip2px(mApp, 20), Util.dip2px(mApp, 20));
        mTVRemarkStr.setCompoundDrawables(mRemarkDrawable, null, null, null);
        mTVGuJia = getViewById(R.id.main_tv_gujia); // 估价

        // 派单toolbar
        mRLPushOrder = getViewById(R.id.pushorder_toolbar); // 派单toolbar
        mTVPushOrderCancel = getViewById(R.id.pushorder_cancel); // 取消派单
        mIVPushOrderBack = getViewById(R.id.pushorder_back); // 派单返回
        mTVPushOrderTitle = getViewById(R.id.pushorder_title); // 派单标题
        wv = getViewById(R.id.wv);// 派单动画

        mRLAcceptOrder = getViewById(R.id.main_rl_acceptorder); // 司机接单区域
        mTVDriverName = getViewById(R.id.main_tv_drivername); // 接单司机名称
        mIVDriverHead = getViewById(R.id.main_iv_driverhead); // 接单司机头像
        mIVDriverTel = getViewById(R.id.main_iv_drivertel); // 接单司机电话
        refresh_driver = getViewById(R.id.refresh_driver); // 接单司机电话

        //        LocationResult = (TextView) findViewById(R.id.textView1);
//        LocationResult.setMovementMethod(ScrollingMovementMethod.getInstance());

    }

    private void initLocationPermissiion() {
        PermissionUtils permissionUtils = new PermissionUtils(this);
        if (permissionUtils.isRequesLocationPermissions()) {
            initLocation();
        } else {
            permissionUtils.requesLocationPermissions();
        }
    }

    public void initLocation() {
        // -----------location config ------------
        locationService = ((App) getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        int type = getIntent().getIntExtra("from", 0);
        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            locationService.setLocationOption(locationService.getOption());
        }
        locationService.start();// 定位SDK
    }

    @Override
    protected void setListener() {
        mIVNavigation.setOnClickListener(this);
        mDrawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            }

            @Override
            public void onDrawerStateChanged(int newState) {
            }
        });
        mLLMyOrder.setOnClickListener(this);
        mLLAccount.setOnClickListener(this);
        mLLMsg.setOnClickListener(this);
        mLLMyAdvise.setOnClickListener(this);
        mLLSetting.setOnClickListener(this);
        mLLLuckDraw.setOnClickListener(this);
        mLLPartner.setOnClickListener(this);
        mLLEnroll.setOnClickListener(this);
        mTVLogout.setOnClickListener(this);

        mIVPosition.setOnClickListener(this);
        mTVDaily.setOnClickListener(this);
        mTVYuYue.setOnClickListener(this);
        mTVChangTu.setOnClickListener(this);

        mTVDailyStartLoc.setOnClickListener(this);
        mTVDailyEndLoc.setOnClickListener(this);
        mTVDailyOneOrder.setOnClickListener(this);
        mTVDailyDCall.setOnClickListener(this);

        mLLYuYueStartTime.setOnClickListener(this);
        mTVYuYueStartLoc.setOnClickListener(this);
        mTVYuYueEndLoc.setOnClickListener(this);

        mLLChangTuStartTime.setOnClickListener(this);
        mTVChangTuStartLoc.setOnClickListener(this);
        mTVChangTuEndLoc.setOnClickListener(this);

        mIVOrderBack.setOnClickListener(this);
        mLLDCount.setOnClickListener(this);
        mLLStartTime.setOnClickListener(this);
        mTVStartLoc.setOnClickListener(this);
        mTVEndLoc.setOnClickListener(this);
        mTVMPerson.setOnClickListener(this);
        mTVPayType.setOnClickListener(this);
        mLLRemark.setOnClickListener(this);
        mLLGuJia.setOnClickListener(this);
        mTVOrder.setOnClickListener(this);

        mIVPushOrderBack.setOnClickListener(this);
        mTVPushOrderCancel.setOnClickListener(this);

        mIVDriverTel.setOnClickListener(this);


        refresh_driver.setOnClickListener(this);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        Glide.with(mApp).load("http://pic7.nipic.com/20100518/3409334_031036048098_2.jpg").into(mIVHead);

        initLocationPermissiion();

        mGeoSearch = GeoCoder.newInstance();
        mGeoSearch.setOnGetGeoCodeResultListener(geoCoderResultListener);
        mRoutePlanSearch = RoutePlanSearch.newInstance();
        mRoutePlanSearch.setOnGetRoutePlanResultListener(routePlanResultListener);

        initDatePicker();
        diyUpdate();

        // Push: 以apikey的方式登录，一般放在主Activity的onCreate中。
        // 这里把apikey存放于manifest文件中，只是一种存放方式，
        // 您可以用自定义常量等其它方式实现，来替换参数中的Utils.getMetaValue(PushDemoActivity.this,
        // "api_key")
//        ！！请将AndroidManifest.xml api_key 字段值修改为自己的 api_key 方可使用 ！！
//        ！！ATTENTION：You need to modify the value of api_key to your own in AndroidManifest.xml to use this Demo !!
        // 启动百度push
        PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, Util.getMetaValue(this, "api_key"));
//        regToken();
        // Push: 如果想基于地理位置推送，可以打开支持地理位置的推送的开关
        // PushManager.enableLbs(getApplicationContext());

        /**
         * 以下通知栏设置2选1。使用默认通知时，无需添加以下设置代码。
         */

        // 1.默认通知
        // 若您的应用需要适配Android O（8.x）系统，且将目标版本targetSdkVersion设置为26及以上时：
        // SDK提供设置Android O（8.x）新特性---通知渠道的设置接口。
        // 若不额外设置，SDK将使用渠道名默认值"Push"；您也可以仿照以下3行代码自定义channelId/channelName。
        // 注：非targetSdkVersion 26的应用无需以下调用且不会生效
//        BasicPushNotificationBuilder bBuilder = new BasicPushNotificationBuilder();
//        bBuilder.setChannelId("testDefaultChannelId");
//        bBuilder.setChannelName("testDefaultChannelName");
        // PushManager.setDefaultNotificationBuilder(this, bBuilder); //使自定义channel生效

        // 2.自定义通知
        // 设置自定义的通知样式，具体API介绍见用户手册
        // 请在通知推送界面中，高级设置->通知栏样式->自定义样式，选中并且填写值：1，
        // 与下方代码中 PushManager.setNotificationBuilder(this, 1, cBuilder)中的第二个参数对应
//        CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
//                R.layout.notification_custom_builder,
//                R.id.notification_icon,
//                R.id.notification_title,
//                R.id.notification_text);
//
//        cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
//        cBuilder.setNotificationDefaults(Notification.DEFAULT_VIBRATE);
//        cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
//        cBuilder.setLayoutDrawable(R.drawable.simple_notification_icon);
//        cBuilder.setNotificationSound(Uri.withAppendedPath(
//                Audio.Media.INTERNAL_CONTENT_URI, "6").toString());
        // 若您的应用需要适配Android O（8.x）系统，且将目标版本targetSdkVersion设置为26及以上时：
        // 可自定义channelId/channelName, 若不设置则使用默认值"Push"；
        // 注：非targetSdkVersion 26的应用无需以下2行调用且不会生效
//        cBuilder.setChannelId("testId");
//        cBuilder.setChannelName("testName");
        // 推送高级设置，通知栏样式设置为下面的ID，ID应与server下发字段notification_builder_id值保持一致
//        PushManager.setNotificationBuilder(this, 1, cBuilder);
    }

    // 信鸽推送（测试）
    void regToken() {
        XGPushManager.registerPush(getApplicationContext(), new XGIOperateCallback() {
            @Override
            public void onSuccess(Object o, int i) {
                showToast(o.toString());
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(o.toString());
            }

            @Override
            public void onFail(Object o, int i, String s) {
                showToast(o.toString() + s);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
        if (userModel != null) {
            mTVNickName.setText(userModel.getNickname());
            mTVTel.setText(userModel.getMobile());
            String vip = userModel.getUser_type();
            String vipStr = "会员类型：";
            if (vip != null) {
                if (vip.equals("0")) {
                    vipStr += "非会员";
                } else if (vip.equals("1")) {
                    vipStr += "普通会员";
                } else if (vip.equals("2")) {
                    vipStr += "合作伙伴";
                } else if (vip.equals("3")) {
                    vipStr += "超级会员";
                }
            }
            mTVVipType.setText(vipStr);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onStop() {
//        locationService.unregisterListener(mListener); //注销掉监听
//        locationService.stop(); //停止定位服务
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        mMapView = null;
        mRoutePlanSearch.destroy();
        mGeoSearch.destroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.navigation: // 侧边菜单
                if (userModel != null)
                    mDrawer.openDrawer(GravityCompat.START);
                else {
                    startActivity(new Intent(mApp, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                }
                break;
            case R.id.drawer_ll_myorder:  // 订单
                startActivity(new Intent(mApp, MyOrderActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                break;
            case R.id.drawer_ll_myaccount: // 账户
                startActivity(new Intent(mApp, MyAccountActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                break;
            case R.id.drawer_ll_mymsg: // 消息
                String mParam2 = "";
                if (userModel != null) {
                    mParam2 = "user_id=" + userModel.getUser_id() + "&fid=" + SPUtils.get(mApp, "fid", "-1");
                }
                startActivity(new Intent(mApp, WebViewActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                        .putExtra("url", Constants.MSG_URL)
                        .putExtra("param", mParam2)
                        .putExtra("title", "消息"));
                break;
            case R.id.drawer_ll_myadvise: // 意见
                String mParam3 = "";
                if (userModel != null) {
                    mParam3 = "user_id=" + userModel.getUser_id();
                }
                startActivity(new Intent(mApp, WebViewActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                        .putExtra("url", Constants.ADVICE_URL)
                        .putExtra("param", mParam3)
                        .putExtra("title", "意见反馈"));
                break;
            case R.id.drawer_ll_setting: // 设置
                startActivity(new Intent(mApp, SettingActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                break;
            case R.id.drawer_ll_luckdraw: // 幸运转盘
                startActivity(new Intent(mApp, WebViewActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).putExtra("url", Constants.TURNTABLE_URL).putExtra("title", "幸运转盘"));
                break;
            case R.id.drawer_ll_partner: // 申请合作伙伴
                String mParam = "";
                if (userModel != null) {
                    mParam = "user_id=" + userModel.getUser_id() + "&fid=" + SPUtils.get(mApp, "fid", "-1");
                }
                startActivity(new Intent(mApp, WebViewActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                        .putExtra("url", Constants.PARTNER_URL)
                        .putExtra("param", mParam)
                        .putExtra("title", "申请合作伙伴"));
                break;
            case R.id.drawer_ll_enroll: // 司机报名
                startActivity(new Intent(mApp, EnrollActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                break;
            case R.id.drawer_tv_logout: // 退出
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("提示");
                builder.setMessage("是否退出登录");
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                SPUtils.remove(mApp, "usermodel");
                                startActivity(new Intent(mApp, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                                mDrawer.closeDrawers();
                                dialog.dismiss();
                            }
                        });
                builder.setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;
            case R.id.main_iv_position: // 手动定位
                locationService.start();
                break;
            case R.id.main_tv_way_daily: // 日常
                setWayTab(0);
                break;
            case R.id.main_tv_way_yuyue: // 预约
                setWayTab(1);
                break;
            case R.id.main_tv_way_changtu: // 长途
                setWayTab(2);
                break;
            case R.id.daily_tv_startLoc: // 日常-出发地
                if (userModel == null) {
                    startActivity(new Intent(mApp, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                    return;
                }
                 startActivityForResult(new Intent(mApp, SearchLocActivity.class)
                         .putExtra(Constants.CONFIG_INTENT_SECRCH_TYPE,"start")
                        .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), Constants.REQUEST_CODE_USER_NORMAL_START_ADDRESS);

                break;
            case R.id.daily_tv_endLoc: // 日常-目的地
                if (userModel == null) {
                    startActivity(new Intent(mApp, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                    return;
                }

                startActivityForResult(new Intent(mApp, SearchLocActivity.class)
                        .addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), Constants.REQUEST_CODE_USER_NORMAL_END_ADDRESS);
                break;
            case R.id.daily_tv_oneorder: // 日常-一键下单
                if (userModel == null) {
                    startActivity(new Intent(mApp, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                    return;
                }
                makeOrder();
                break;
            case R.id.daily_tv_dcall: // 日常-代叫
                if (userModel == null) {
                    startActivity(new Intent(mApp, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                    return;
                }

                mTVStartLoc.setText(mTVStartLoc.getText().toString());
                mRLOrder.setVisibility(View.VISIBLE);
                mLLForm.setVisibility(View.VISIBLE);
                mIVPosition.setVisibility(View.GONE);
                mLLWay.setVisibility(View.GONE);
                mVPMain.setVisibility(View.GONE);
                mTVOrderTitle.setText("确认下单");

                mLLStartTime.setVisibility(View.GONE);
                mTVPayType.setVisibility(View.GONE);
                mLLRemark.setVisibility(View.GONE);
                mLLDCount.setVisibility(View.VISIBLE);
                mLLMPerson.setVisibility(View.VISIBLE);
                break;
            case R.id.yuyue_ll_startTime: // 预约-出发时间区域
                if (userModel == null) {
                    startActivity(new Intent(mApp, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                    return;
                }

                mCDPYuYue.show(DateUtils.getCurrentTime());
                break;
            case R.id.yuyue_tv_startLoc: // 预约-出发地
                if (userModel == null) {
                    startActivity(new Intent(mApp, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                    return;
                }
                break;
            case R.id.yuyue_tv_endLoc: // 预约-目的地
                if (userModel == null) {
                    startActivity(new Intent(mApp, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                    return;
                }

                startActivityForResult(new Intent(mApp, SearchLocActivity.class).
                        addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), 1001);
                break;
            case R.id.changtu_ll_startTime: // 长途-出发时间区域
                if (userModel == null) {
                    startActivity(new Intent(mApp, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                    return;
                }

                mCDPChangtu.show(DateUtils.getCurrentTime());
                break;
            case R.id.changtu_tv_startLoc: // 长途-出发地
                if (userModel == null) {
                    startActivity(new Intent(mApp, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                    return;
                }

                break;
            case R.id.changtu_tv_endLoc: // 长途-目的地
                if (userModel == null) {
                    startActivity(new Intent(mApp, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
                    return;
                }

                startActivityForResult(new Intent(mApp, SearchLocActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), 1002);
                break;
            case R.id.order_back: // 下单-返回
                resetOrder();
                mRLOrder.setVisibility(View.GONE);
                mLLForm.setVisibility(View.GONE);
                break;
            case R.id.main_ll_dCount: // 下单-司机数量区域
                showDriverCountPopWin(v);
                break;
            case R.id.popwin_drivercount_one: // 司机数量 1
                mDriverCount = "1";
                mTVDCount.setText(mDriverCount + "名司机");
                mDriverCountPopWin.dismiss();
//                mTVEndLoc.setVisibility(View.VISIBLE);
                break;
            case R.id.popwin_drivercount_two: // 司机数量 2
                mDriverCount = "2";
                mTVDCount.setText(mDriverCount + "名司机");
                mDriverCountPopWin.dismiss();
//                mTVEndLoc.setText("");
//                mEndLat = 0;
//                mEndLon = 0;
//                mTVEndLoc.setVisibility(View.GONE);
//                mTVGuJia.setText("");
//                mLLGuJia.setVisibility(View.GONE);
                break;
            case R.id.popwin_drivercount_three: // 司机数量 3
                mDriverCount = "3";
                mTVDCount.setText(mDriverCount + "名司机");
                mDriverCountPopWin.dismiss();
//                mTVEndLoc.setText("");
//                mEndLat = 0;
//                mEndLon = 0;
//                mTVEndLoc.setVisibility(View.GONE);
//                mTVGuJia.setText("");
//                mLLGuJia.setVisibility(View.GONE);
                break;
            case R.id.main_ll_startTime: // 下单-出发时间区域
                mCDPOrder.show(DateUtils.getCurrentTime());
                break;
            case R.id.main_tv_startLoc: // 下单-出发地
                break;
            case R.id.main_tv_endLoc: // 下单-目的地
                startActivityForResult(new Intent(mApp, SearchLocActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), 1003);
                break;
            case R.id.main_tv_mperson: // 下单-联系人
                startActivityForResult(new Intent(mApp, ModifyPersonActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT), 1004);
                break;
            case R.id.main_tv_paytype: // 下单-支付方式
                break;
            case R.id.main_ll_remark: // 下单-备注区域
                startActivityForResult(new Intent(mApp, AddNoteActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).putExtra("note", mTVRemark.getText().toString().trim()), 1005);
                break;
            case R.id.main_ll_gujia: // 下单-估价区域
                break;
            case R.id.main_tv_oneorder: // 下单-提交订单
                if (mLLDCount.getVisibility() == View.VISIBLE) {
                    makeDOrder();
                } else {
                    makeOrder();
                }
                break;
            case R.id.pushorder_back: // 派单返回
                wv.stop();
                wv.setVisibility(View.GONE);
                stopTimer2();
                isPushOrder = false;
                setMapAllGestures(!isPushOrder);
                resetOrder();
                mIVPosition.setVisibility(View.VISIBLE);
                mRLPushOrder.setVisibility(View.GONE);
                break;
            case R.id.pushorder_cancel: // 取消派单
                new AlertDialog.Builder(this).setTitle("提示")
                        .setMessage("确定要取消订单吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                wv.stop();
                                wv.setVisibility(View.GONE);
                                stopTimer2();
                                stopTimer();
                                cancelOrder();
                            }
                        })
                        .setNegativeButton("取消", null).create().show();
                break;
            case R.id.main_iv_drivertel: // 接单司机电话
                callTel((String) mIVDriverTel.getTag());
                break;

            case R.id.refresh_driver: // 获取附近司机

                if (mCurGeoCodeResult == null) {
                    ToastUtil.show("未获取到您的定位信息");
                } else {
                    setRefreshDriver(mCurGeoCodeResult);
                }

                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_CODE_USER_NORMAL_END_ADDRESS) { // 日常单-目的地
            if (resultCode == 200) {
                PoiInfo poiInfo = data.getParcelableExtra("endPoiInfo");
                mTVEndLoc.setText(poiInfo.name);
                mEndLat = poiInfo.location.latitude;
                mEndLon = poiInfo.location.longitude;
                mRLOrder.setVisibility(View.VISIBLE);
                mLLForm.setVisibility(View.VISIBLE);
                mIVPosition.setVisibility(View.GONE);
                mLLWay.setVisibility(View.GONE);
                mVPMain.setVisibility(View.GONE);
                mTVOrderTitle.setText("确认下单");
                mOrderType = "1";

                mLLStartTime.setVisibility(View.GONE);
                mTVPayType.setVisibility(View.GONE);
                mLLRemark.setVisibility(View.GONE);
                mLLDCount.setVisibility(View.GONE);
                mLLMPerson.setVisibility(View.GONE);
                mLLGuJia.setVisibility(View.VISIBLE);
                mTVGuJia.setText("");

                PlanNode stNode = PlanNode.withLocation(new LatLng(mStartLat, mStartLon));
                PlanNode enNode = PlanNode.withLocation(poiInfo.location);
                mRoutePlanSearch.drivingSearch((new DrivingRoutePlanOption())
                        .from(stNode)
                        .to(enNode));
            }
        } else if (requestCode == Constants.REQUEST_CODE_USER_NORMAL_START_ADDRESS) { // 日常单-出发地
            if (resultCode == 200) {
                PoiInfo poiInfo = data.getParcelableExtra("endPoiInfo");
                mTVStartLoc.setText(poiInfo.name);

                mStartLat = poiInfo.location.latitude;
                mStartLon = poiInfo.location.longitude;

                mRLOrder.setVisibility(View.VISIBLE);
                mLLForm.setVisibility(View.VISIBLE);

                mIVPosition.setVisibility(View.GONE);
                mLLWay.setVisibility(View.GONE);
                mVPMain.setVisibility(View.GONE);
                mTVOrderTitle.setText("确认下单");
                mOrderType = "1";

                mLLStartTime.setVisibility(View.GONE);
                mTVPayType.setVisibility(View.GONE);
                mLLRemark.setVisibility(View.GONE);
                mLLDCount.setVisibility(View.GONE);
                mLLMPerson.setVisibility(View.GONE);
                mLLGuJia.setVisibility(View.VISIBLE);

                mTVGuJia.setText("");

                //根据起始地点计算具体 调接口获取价格
//                PlanNode stNode = PlanNode.withLocation(new LatLng(mStartLat, mStartLon));
//                PlanNode enNode = PlanNode.withLocation(poiInfo.location);
//                mRoutePlanSearch.drivingSearch((new DrivingRoutePlanOption())
//                        .from(stNode)
//                        .to(enNode));
            }
        } else if (requestCode == 1001) { // 预约单
            if (resultCode == 200) {
                PoiInfo poiInfo = data.getParcelableExtra("endPoiInfo");
                mTVEndLoc.setText(poiInfo.name);
                mEndLat = poiInfo.location.latitude;
                mEndLon = poiInfo.location.longitude;
                mRLOrder.setVisibility(View.VISIBLE);
                mLLForm.setVisibility(View.VISIBLE);
                mIVPosition.setVisibility(View.GONE);
                mLLWay.setVisibility(View.GONE);
                mVPMain.setVisibility(View.GONE);
                mTVOrderTitle.setText("确认预约下单");
                mOrderType = "2";

                if (!TextUtils.equals("", mTVYuYueStartTime.getText().toString())) {
                    mTVStartTime.setText(mTVYuYueStartTime.getText());
                }
                mLLStartTime.setVisibility(View.VISIBLE);
                mTVPayType.setVisibility(View.VISIBLE);
                mLLRemark.setVisibility(View.VISIBLE);
                mLLDCount.setVisibility(View.GONE);
                mLLMPerson.setVisibility(View.GONE);
                mLLGuJia.setVisibility(View.VISIBLE);
                mTVGuJia.setText("");

                PlanNode stNode = PlanNode.withLocation(new LatLng(mStartLat, mStartLon));
                PlanNode enNode = PlanNode.withLocation(poiInfo.location);
                mRoutePlanSearch.drivingSearch((new DrivingRoutePlanOption())
                        .from(stNode)
                        .to(enNode));
            }
        } else if (requestCode == 1002) { // 长途单
            if (resultCode == 200) {
                PoiInfo poiInfo = data.getParcelableExtra("endPoiInfo");
                mTVEndLoc.setText(poiInfo.name);
                mEndLat = poiInfo.location.latitude;
                mEndLon = poiInfo.location.longitude;
                mRLOrder.setVisibility(View.VISIBLE);
                mLLForm.setVisibility(View.VISIBLE);
                mIVPosition.setVisibility(View.GONE);
                mLLWay.setVisibility(View.GONE);
                mVPMain.setVisibility(View.GONE);
                mTVOrderTitle.setText("确认长途下单");
                mOrderType = "3";

                if (!TextUtils.equals("", mTVChangTuStartTime.getText().toString())) {
                    mTVStartTime.setText(mTVChangTuStartTime.getText());
                }
                mLLStartTime.setVisibility(View.VISIBLE);
                mTVPayType.setVisibility(View.VISIBLE);
                mLLRemark.setVisibility(View.VISIBLE);
                mLLDCount.setVisibility(View.GONE);
                mLLMPerson.setVisibility(View.GONE);
                mLLGuJia.setVisibility(View.VISIBLE);
                mTVGuJia.setText("");

                PlanNode stNode = PlanNode.withLocation(new LatLng(mStartLat, mStartLon));
                PlanNode enNode = PlanNode.withLocation(poiInfo.location);
                mRoutePlanSearch.drivingSearch((new DrivingRoutePlanOption())
                        .from(stNode)
                        .to(enNode));
            }
        } else if (requestCode == 1003) { // 下单目的地
            if (resultCode == 200) {
                PoiInfo poiInfo = data.getParcelableExtra("endPoiInfo");
                mTVEndLoc.setText(poiInfo.name);
                mEndLat = poiInfo.location.latitude;
                mEndLon = poiInfo.location.longitude;
                mLLGuJia.setVisibility(View.VISIBLE);
                mTVGuJia.setText("");

                PlanNode stNode = PlanNode.withLocation(new LatLng(mStartLat, mStartLon));
                PlanNode enNode = PlanNode.withLocation(poiInfo.location);
                mRoutePlanSearch.drivingSearch((new DrivingRoutePlanOption())
                        .from(stNode)
                        .to(enNode));
            }
        } else if (requestCode == 1004) { // 修改联系人
            if (resultCode == 200) {
                mTVMPerson.setText(data.getStringExtra("tel"));
            }
        } else if (requestCode == 1005) { // 添加备注
            if (resultCode == 200) {
                mTVRemark.setText(data.getStringExtra("note"));
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {

            case PermissionUtils.MY_PERMISSIONS_ACCESS_FINE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initLocation();
                    LogsUtil.normal("获取了定位权限");
                } else {
                    LogsUtil.normal("拒绝了定位权限");
                    ToastUtil.show("未获取定位权限，请前去设置-权限中允许");
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mRLOrder.getVisibility() == View.VISIBLE) {
                    resetOrder();
                    mRLOrder.setVisibility(View.GONE);
                    mLLForm.setVisibility(View.GONE);
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("提示")
                            .setMessage("确定要退出吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                    System.exit(0);
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                    builder.create().show();
                }
                break;

            default:
                break;
        }
        return true;
    }

    //软件更新用这个
    private void diyUpdate() {

        isShowDownloadProgress = true;

        String path = Environment.getExternalStorageDirectory().getAbsolutePath();

        Map<String, String> params = new HashMap<String, String>();
//
//        params.put("appKey", "ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f");
        params.put("version", AppUpdateUtils.getVersionName(this));

//        params.put("key1", "value2");
//        params.put("key2", "value3");

        new UpdateAppManager
                .Builder()
                //必须设置，当前Activity
                .setActivity(this)
                //必须设置，实现httpManager接口的对象
                .setHttpManager(new OkGoUpdateHttpUtil())
                //必须设置，更新地址
                .setUpdateUrl(mUpdateUrl)

                //以下设置，都是可选
                //设置请求方式，默认get
                .setPost(false)
                //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
                .setParams(params)
                //设置apk下砸路径，默认是在下载到sd卡下/Download/1.0.0/test.apk
                .setTargetPath(path)
                //设置appKey，默认从AndroidManifest.xml获取，如果，使用自定义参数，则此项无效
//                .setAppKey("ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f")

                .build()
                //检测是否有新版本
                .checkNewApp(new UpdateCallback() {
                    /**
                     * 解析json,自定义协议
                     *
                     * @param json 服务器返回的json
                     * @return UpdateAppBean
                     */
                    @Override
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        try {
                            JSONObject jsonObject = new JSONObject(json);
                            updateAppBean
                                    //（必须）是否更新Yes,No
                                    .setUpdate(jsonObject.optString("update"))
                                    //（必须）新版本号，
                                    .setNewVersion(jsonObject.optString("new_version"))
                                    //（必须）下载地址
                                    .setApkFileUrl(jsonObject.optString("apk_file_url"))

                                    //（必须）更新内容
                                    .setUpdateLog(jsonObject.optString("update_log"))

                                    //大小，不设置不显示大小，可以不设置
                                    .setTargetSize(jsonObject.optString("target_size"))
                                    //是否强制更新，可以不设置
                                    .setConstraint(false);
                            //设置md5，可以不设置
//                                    .setNewMd5(jsonObject.optString("new_md51"))

//                            updateAppBean.setApkFileUrl("http:\\/\\/120.27.233.26\\/TaobaoDemoApp\\/src\\/app\\/app_v1.0.apk");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return updateAppBean;
                    }

                    /**
                     * 有新版本
                     *
                     * @param updateApp        新版本信息
                     * @param updateAppManager app更新管理器
                     */
                    @Override
                    public void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                        //强制更新，
                        if (updateApp.isConstraint()) {

                        } else {

                        }
                        //自定义对话框
                        showDiyDialog(updateApp, updateAppManager);
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {
                        CProgressDialogUtils.showProgressDialog(MainActivity.this);
                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {
                        CProgressDialogUtils.cancelProgressDialog(MainActivity.this);
                    }

                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp(String error) {
                        Toast.makeText(MainActivity.this, "没有新版本", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    /**
     * 自定义对话框
     *
     * @param updateApp
     * @param updateAppManager
     */
    private void showDiyDialog(final UpdateAppBean updateApp, final UpdateAppManager updateAppManager) {
        String targetSize = updateApp.getTargetSize();
        String updateLog = updateApp.getUpdateLog();

        String msg = "";

        if (!TextUtils.isEmpty(targetSize)) {
            msg = "新版本大小：" + targetSize + "\n\n";
        }

        if (!TextUtils.isEmpty(updateLog)) {
            msg += updateLog;
        }

        new AlertDialog.Builder(this)
                .setTitle(String.format("是否升级到%s版本？", updateApp.getNewVersion()))
                .setMessage(msg)
                .setPositiveButton("升级", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //显示下载进度
                        if (isShowDownloadProgress) {
                            updateAppManager.download(new DownloadService.DownloadCallback() {
                                @Override
                                public void onStart() {
                                    HProgressDialogUtils.showHorizontalProgressDialog(MainActivity.this, "下载进度", false);
                                }

                                /**
                                 * 进度
                                 *
                                 * @param progress  进度 0.00 -1.00 ，总大小
                                 * @param totalSize 总大小 单位B
                                 */
                                @Override
                                public void onProgress(float progress, long totalSize) {
                                    HProgressDialogUtils.setProgress(Math.round(progress * 100));
                                }

                                /**
                                 *
                                 * @param total 总大小 单位B
                                 */
                                @Override
                                public void setMax(long total) {

                                }


                                @Override
                                public boolean onFinish(File file) {
                                    HProgressDialogUtils.cancel();
                                    return true;
                                }

                                @Override
                                public void onError(String msg) {
                                    Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                                    HProgressDialogUtils.cancel();

                                }
                            });
                        } else {
                            //不显示下载进度
                            updateAppManager.download();
                        }


                        dialog.dismiss();
                    }
                })
                .setNegativeButton("暂不升级", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }


    // 生成订单
    private void makeOrder() {
        String orderType = mOrderType;


        String sAddress = mTVStartLoc.getText().toString().trim();
        String sLon = String.valueOf(mStartLon);
        String sLat = String.valueOf(mStartLat);


        String eAddress = mTVEndLoc.getText().toString().trim();
        String eLon = String.valueOf(mEndLon);
        String eLat = String.valueOf(mEndLat);
        String uId = userModel.getUser_id();

        String note = mTVRemark.getText().toString().trim();
        String sTime = DateUtils.getTimestamp(mTVStartTime.getText().toString(), "yyyy-MM-dd HH:mm");
        String key = MD5.getMessageDigest((Constants.BASE_KEY + uId).getBytes());

        if (mStartLat == 0) {
            showToast("请设置出发地");
            return;
        }
        if (orderType.equals("2") || orderType.equals("3")) {
            if (mEndLat == 0) {
                showToast("请设置目的地");
                return;
            }
            if (sTime == null) {
                showToast("请选择出发时间");
                return;
            }
        }

        // 禁止地图操作
        isPushOrder = true;
        setMapAllGestures(!isPushOrder);

        mEngine.makeOrder(orderType, sAddress, sLon, sLat, eAddress, eLon, eLat, uId, note, key, sTime).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String str = response.body().string();
                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");

                    if (status == 200) {
                        showToast("创建订单成功");
                        mRLOrder.setVisibility(View.GONE);
                        mLLForm.setVisibility(View.GONE);
                        resetOrder();
                        mCurOrderList = "";
                        for (int i = 0; i < jo.getJSONArray("result").length(); i++) {
                            if (i == 0) {
                                mCurOrderList += jo.getJSONArray("result").get(i);
                            } else {
                                mCurOrderList += "," + jo.getJSONArray("result").get(i);
                            }
                        }

                        LogsUtil.orderPush("创建订单成功" + str + "mCurOrderList" + mCurOrderList);

                        pushOrder(mCurOrderList);

                    } else if (status == 106) {
                        showToast("加盟商不存在");
                    } else if (status == 201) {
                        showToast("用户不存在");
                    } else if (status == 301) {
                        showToast("有订单未完成");
                    } else if (status == 302) {
                        showToast("有未支付的订单，无法下单");
                        startActivity(new Intent(mApp, OrderDetailActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).putExtra("orderid", jo.getJSONArray("result").get(0).toString()));
                    } else if (status == 401) {
                        showToast("预约时间不正确");
                    } else if (status == 100) {
                        showToast("下单失败");
                    } else {
                        showToast("下单异常");
                    }

                    if (status != 200) {
                        // 允许地图操作
                        isPushOrder = false;
                        setMapAllGestures(!isPushOrder);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                // 允许地图操作
                isPushOrder = false;
                setMapAllGestures(!isPushOrder);
            }
        });
    }

    // 生成代叫订单
    private void makeDOrder() {
        String moible = mTVMPerson.getText().toString().trim();
        if (moible == null || moible.equals("")) {
            moible = userModel.getMobile();
        }
        String sAddress = mTVStartLoc.getText().toString().trim();
        String sLon = String.valueOf(mStartLon);
        String sLat = String.valueOf(mStartLat);
        String eAddress = mTVEndLoc.getText().toString().trim();
        String eLon = String.valueOf(mEndLon);
        String eLat = String.valueOf(mEndLat);
        String uId = userModel.getUser_id();
        String note = mTVRemark.getText().toString().trim();
        String count = mDriverCount;
        String key = MD5.getMessageDigest((moible + Constants.BASE_KEY + uId).getBytes());

        if (mStartLat == 0) {
            showToast("请设置出发地");
            return;
        }

        // 禁止地图操作
        isPushOrder = true;
        setMapAllGestures(!isPushOrder);

        mEngine.makeDOrder(moible, sAddress, sLon, sLat, eAddress, eLon, eLat, uId, note, count, key).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String str = response.body().string();
                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");
                    if (status == 200) {
                        showToast("创建订单成功");
                        mRLOrder.setVisibility(View.GONE);
                        mLLForm.setVisibility(View.GONE);
                        resetOrder();
                        mCurOrderList = "";
                        for (int i = 0; i < jo.getJSONArray("result").length(); i++) {
                            if (i == 0) {
                                mCurOrderList += jo.getJSONArray("result").get(i);
                            } else {
                                mCurOrderList += "," + jo.getJSONArray("result").get(i);
                            }
                        }
                        pushOrder(mCurOrderList);
                    } else if (status == 106) {
                        showToast("加盟商不存在");
                    } else if (status == 201) {
                        showToast("用户不存在");
                    } else if (status == 301) {
                        showToast("有订单未完成");
                    } else if (status == 302) {
                        showToast("有未支付的订单，无法下单");
                        startActivity(new Intent(mApp, OrderDetailActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).putExtra("orderid", jo.getJSONArray("result").get(0).toString()));
                    } else if (status == 100) {
                        showToast("下单失败");
                    } else {
                        showToast("下单异常");
                    }

                    if (status != 200) {
                        // 允许地图操作
                        isPushOrder = false;
                        setMapAllGestures(!isPushOrder);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                // 允许地图操作
                isPushOrder = false;
                setMapAllGestures(!isPushOrder);
            }
        });
    }

    // 订单派发接口
    private void pushOrder(final String orderlist) {
        if (orderlist != null && !orderlist.trim().equals("")) {

            mVPMain.setVisibility(View.GONE);
            mLLWay.setVisibility(View.GONE);
            mIVPosition.setVisibility(View.GONE);
            mRLPushOrder.setVisibility(View.VISIBLE);
            mTVPushOrderTitle.setText("正在派单");
            mRLTip.setVisibility(View.GONE);

            LogsUtil.orderPush("订单派发" + orderlist);

            mEngine.pushOrder(orderlist, userModel.getUser_id(), MD5.getMessageDigest((orderlist + Constants.BASE_KEY + userModel.getUser_id()).getBytes())).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String str = response.body().string();
                        JSONObject jo = new JSONObject(str);
                        int status = jo.getInt("status");
                        String msg = jo.getString("msg");

                        LogsUtil.orderPush("订单派发后台返回" + str);

                        if (status == 200) {
//                            wv.stop();
//                            wv.setVisibility(View.GONE);
//                            getOrder();

                            wv.start(); // 开始动画
                            wv.setVisibility(View.VISIBLE);
                            currentOrderId = orderlist.split(",")[0];
                            startTimer2(orderlist.split(",")[0]);
                        } else if (status == 201) {
                            showToast("用户不存在");
                        } else if (status == 401) {
                            showToast("参数错误");
                        } else if (status == 402) {
                            showToast("无可派订单");
                        } else if (status == 503 || status == 504 || status == 505) {
                            showToast("订单超时，无人接单");
                        } else if (status == 100) {
                            showToast("派单失败");
                        } else {
                            showToast("派单异常");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
//                    finally {
//                        resetOrder();
//                        mIVPosition.setVisibility(View.VISIBLE);
//                        mRLPushOrder.setVisibility(View.GONE);
//                        // 允许地图操作
//                        isPushOrder = false;
//                        setMapAllGestures(!isPushOrder);
//                        wv.stop();
//                        wv.setVisibility(View.GONE);
//                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    resetOrder();
                    mIVPosition.setVisibility(View.VISIBLE);
                    mRLPushOrder.setVisibility(View.GONE);
                    // 允许地图操作
                    isPushOrder = false;
                    setMapAllGestures(!isPushOrder);

                    LogsUtil.orderPush("订单派发" + "onFailure");


                }
            });
        }
    }

    // 查询订单信息
    private void getOrder(String orderid) {
        final String order_id = orderid;
        mEngine.getOrderInfo(orderid, userModel.getUser_id(), MD5.getMessageDigest((orderid + Constants.BASE_KEY + userModel.getUser_id()).getBytes())).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String str = response.body().string();
                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");
                    if (status == 200) {
                        JSONObject jsonObject = jo.getJSONObject("result");
                        if (jsonObject.getString("order_status") != null && jsonObject.getString("order_status").equals("1")) {
                            currentOrderId = order_id;
                            startTimer4CompleteOrder(currentOrderId);
                            //showToast("代驾司机已接单,startTimer4CompleteOrder,currentOrderId="+currentOrderId);
                            wv.stop();
                            wv.setVisibility(View.GONE);
                            stopTimer2(); // 停止获取是否接单
                            mBaiduMap.getUiSettings().setAllGesturesEnabled(true);
                            mRLAcceptOrder.setVisibility(View.VISIBLE);

                            Glide.with(mApp).load(Constants.BASE_URL + jsonObject.getString("head_pic"))
                                    .into(mIVDriverHead);

                            mTVPushOrderTitle.setText("司机已接单");
                            mTVDriverName.setText(jsonObject.getString("sj_name"));
                            mIVDriverTel.setTag(jsonObject.getString("sj_mobile"));
                            curSjId = jsonObject.getString("sj_id");
                            curSjHead = Constants.BASE_URL + jsonObject.getString("head_pic");
                            startTimer(); // 启动定时器 获取司机位置信息

                            mIVPushOrderBack.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    isPushOrder = false;
                                    setMapAllGestures(!isPushOrder);
                                    stopTimer();
                                    mBaiduMap.clear();
                                    mIVPushOrderBack.setOnClickListener(MainActivity.this);
                                    resetOrder();
                                    mIVPosition.setVisibility(View.VISIBLE);
                                    mRLPushOrder.setVisibility(View.GONE);
                                }
                            });
                        }
                    } else if (status == 100) {
                        showToast("获取订单失败");
                    } else if (status == 201) {
                        showToast("用户不存在");
                    } else if (status == 301) {
                        showToast("订单不存在");
                    } else {
                        showToast("获取订单异常");
                    }

//                    if (status != 200) {
//                        resetOrder();
//                        mIVPosition.setVisibility(View.VISIBLE);
//                        mRLPushOrder.setVisibility(View.GONE);
//                        // 允许地图操作
//                        isPushOrder = false;
//                        setMapAllGestures(!isPushOrder);
//                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
//                resetOrder();
//                mIVPosition.setVisibility(View.VISIBLE);
//                mRLPushOrder.setVisibility(View.GONE);
//                // 允许地图操作
//                isPushOrder = false;
//                setMapAllGestures(!isPushOrder);
            }
        });
    }

    String curSjId, curSjHead;

    // 获取接单司机位置信息
    private void getDriverLoc() {
        mEngine.getDriverLoc(curSjId).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String str = response.body().string();
                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");
                    if (status == 200) {
                        mBaiduMap.clear();
                        JSONObject jsonObject = jo.getJSONObject("result");
                        LatLng latLng = new LatLng(jsonObject.getDouble("sb_lat"), jsonObject.getDouble("sb_long"));
                        View view = LayoutInflater.from(mApp).inflate(R.layout.view_driver, null); // 司机渲染
                        Glide.with(mApp).load(curSjHead).into((ImageView) view.findViewById(R.id.view_driver_iv_head));
                        MarkerOptions mo = new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromView(view)).zIndex(9);
                        mBaiduMap.addOverlay(mo);

                    } else if (status == 100) {
                        showToast("获取司机信息失败");
                    } else if (status == 201) {
                        showToast("司机不存在");
                    } else {
                        showToast("获取司机位置信息异常");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }


    public void queryOrderIsCompleted(final String orderId) {

        mEngine.getOrderInfo(orderId, userModel.getUser_id(), MD5.getMessageDigest((orderId + Constants.BASE_KEY + userModel.getUser_id()).getBytes())).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String str = response.body().string();
                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");
                    if (status == 200) {
                        JSONObject jsonObject = jo.getJSONObject("result");
                        if (jsonObject.getString("order_status") != null && (jsonObject.getString("order_status").equals("2"))) {
                            //周围无司机,回到下单页面
                            mTimer4CompleteOrder.cancel();
                            mRLAcceptOrder.setVisibility(View.GONE);
                            wv.stop();
                            wv.setVisibility(View.GONE);
                            stopTimer2();
                            isPushOrder = false;
                            setMapAllGestures(!isPushOrder);
                            resetOrder();
                            mIVPosition.setVisibility(View.VISIBLE);
                            mRLPushOrder.setVisibility(View.GONE);


                            stopTimer();


                            mBaiduMap.clear();
                            String orderid = currentOrderId;
                            currentOrderId = null;
                            stopTimer4CompleteOrder();
                            return;
                        }
                        if (jsonObject.getString("order_status") != null && (jsonObject.getString("order_status").equals("0") || jsonObject.getString("order_status").equals("9"))) {
                            mTimer4CompleteOrder.cancel();
                            mRLAcceptOrder.setVisibility(View.GONE);
                            //订单被重派，回到派单页面
                            mVPMain.setVisibility(View.GONE);
                            mLLWay.setVisibility(View.GONE);
                            mIVPosition.setVisibility(View.GONE);
                            mRLPushOrder.setVisibility(View.VISIBLE);
                            mTVPushOrderTitle.setText("正在派单");
                            mRLTip.setVisibility(View.GONE);
                            wv.start(); // 开始动画
                            wv.setVisibility(View.VISIBLE);
                            currentOrderId = orderId;
                            startTimer2(orderId);
                            return;
                        }
                        if (jsonObject.getString("order_status") != null && jsonObject.getString("order_status").equals("4")) {//代驾结束，待结算
                            String pay_status = jsonObject.getString("pay_status");
                            String is_paypt = jsonObject.getString("is_paypt");
                            //showToast("代驾queryOrderIsCompleted，order_status="+jsonObject.getString("order_status")+",pay_status="+pay_status+"，is_paypt="+is_paypt);
                            if ("1".equals(pay_status)) {//现金支付，默认已支付完成
                                //现金结算跳到主页面

                                wv.stop();
                                wv.setVisibility(View.GONE);
                                stopTimer2();
                                isPushOrder = false;
                                setMapAllGestures(!isPushOrder);
                                resetOrder();
                                mIVPosition.setVisibility(View.VISIBLE);
                                mRLPushOrder.setVisibility(View.GONE);


                                stopTimer();


                                mBaiduMap.clear();
                                String orderid = currentOrderId;
                                currentOrderId = null;
                                stopTimer4CompleteOrder();
                                String mParam = "";
                                if (userModel != null) {
                                    mParam = "user_id=" + userModel.getUser_id() + "&order_id=" + orderid;
                                }
                                startActivity(new Intent(mApp, WebViewActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                                        .putExtra("title", "评价")
                                        .putExtra("url", Constants.COMMENT_URL)
                                        .putExtra("param", mParam)
                                        .putExtra("backToMain", "1"));
                                //showToast("代驾现金结算currentOrderId=null,stopTimer4CompleteOrder");
                            } else if ("1".equals(is_paypt)) {
                                //平台结算跳到订单详情页去支付
                                startActivity(new Intent(mApp, OrderDetailActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).putExtra("orderid", currentOrderId));
                                currentOrderId = null;
                                stopTimer4CompleteOrder();
                                //showToast("代驾平台结算currentOrderId=null,stopTimer4CompleteOrder");
                            }
                        }
                    }
                } catch (IOException e) {
                    currentOrderId = null;
                    stopTimer4CompleteOrder();
                    e.printStackTrace();
                } catch (JSONException e) {
                    currentOrderId = null;
                    stopTimer4CompleteOrder();
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }


    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                getDriverLoc();

            } else if (msg.what == 2) {
                getOrder(msg.obj.toString());
            } else if (msg.what == 3) {
                //查询订单是否已结算或者被重派，跳到相应界面
                String orderId = currentOrderId;
                //showToast("查询订单"+orderId+"是否已结算");
                if (orderId != null && !"".equals(orderId.trim()))
                    queryOrderIsCompleted(orderId);
            }
            super.handleMessage(msg);
        }

        ;
    };

    Timer mTimer; // 定时器，查询司机位置
    TimerTask mTimerTask;

    Timer mTimer2; // 定时器，查询订单是否已被接
    TimerTask mTimerTask2;

    Timer mTimer4CompleteOrder; // 定时器，查询订单是否已结束，需要跳到平台支付
    TimerTask mTimerTask4CompleteOrder;

    private void startTimer() {
        if (mTimer == null) {
            mTimer = new Timer();
        }

        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            };
        }

        if (mTimer != null && mTimerTask != null) {

            mTimer.schedule(mTimerTask, 1000, 60000); // 每60秒执行任务
        }

    }

    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    boolean Timer4CompleteOrder = false;

    private void startTimer4CompleteOrder(final String orderid) {
        if (mTimer4CompleteOrder == null) {
            mTimer4CompleteOrder = new Timer();
        }
        if (mTimerTask4CompleteOrder == null) {

            mTimerTask4CompleteOrder = new TimerTask() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.what = 3;
                    message.obj = orderid;
                    handler.sendMessage(message);
                }
            };
        }

        if (mTimer4CompleteOrder != null && mTimerTask4CompleteOrder != null) {
            if (!Timer4CompleteOrder) {
                Timer4CompleteOrder = true;
                mTimer4CompleteOrder.schedule(mTimerTask4CompleteOrder, 1000, 5000); // 每1秒执行任务
            }

        }

    }

    private void stopTimer4CompleteOrder() {
        if (mTimer4CompleteOrder != null) {
            mTimer4CompleteOrder.cancel();
            mTimer4CompleteOrder = null;
        }

        if (mTimerTask4CompleteOrder != null) {
            mTimerTask4CompleteOrder.cancel();
            mTimerTask4CompleteOrder = null;
        }
        Timer4CompleteOrder = false;
    }


    private void startTimer2(final String orderid) {
        if (mTimer2 == null) {
            mTimer2 = new Timer();
        }

        if (mTimerTask2 == null) {
            mTimerTask2 = new TimerTask() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.what = 2;
                    message.obj = orderid;
                    handler.sendMessage(message);
                }
            };
        }

        if (mTimer2 != null && mTimerTask2 != null)
            mTimer2.schedule(mTimerTask2, 1000, 1000); // 每5秒执行任务
    }

    private void stopTimer2() {
        if (mTimer2 != null) {
            mTimer2.cancel();
            mTimer2 = null;
        }

        if (mTimerTask2 != null) {
            mTimerTask2.cancel();
            mTimerTask2 = null;
        }
    }

    // 取消订单
    private void cancelOrder() {
        mEngine.cancelOrder(mCurOrderList, userModel.getUser_id(), MD5.getMessageDigest((mCurOrderList + Constants.BASE_KEY + userModel.getUser_id()).getBytes())).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String str = response.body().string();
                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");
                    if (status == 200) {
                        resetOrder();
                        isPushOrder = false;
                        setMapAllGestures(!isPushOrder);
                        stopTimer();
                        mBaiduMap.clear();
                        mIVPushOrderBack.setOnClickListener(MainActivity.this);
                        mIVPosition.setVisibility(View.VISIBLE);
                        mRLPushOrder.setVisibility(View.GONE);
                        String mParam = "";
                        if (userModel != null) {
                            mParam = "user_id=" + userModel.getUser_id() + "&order_list=" + mCurOrderList + "&fid=" + SPUtils.get(mApp, "fid", "-1");
                        }
                        startActivity(new Intent(mApp, WebViewActivity.class).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
                                .putExtra("title", "取消原因")
                                .putExtra("url", Constants.CANCEL_URL)
                                .putExtra("param", mParam));
                    } else if (status == 201) {
                        showToast("用户不存在");
                    } else if (status == 301) {
                        showToast("订单不存在");
                    } else if (status == 401) {
                        showToast("当前订单不能取消");
                    } else if (status == 100) {
                        showToast("取消失败");
                    } else {
                        showToast("取消异常");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                resetOrder();
                mIVPosition.setVisibility(View.VISIBLE);
                mRLPushOrder.setVisibility(View.GONE);
            }
        });
    }

    // 初始化日期选择控件
    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date());
        String future = sdf.format(new Date().getTime() + (long) 30 * 24 * 60 * 60 * 1000);
//        currentDate.setText(now.split(" ")[0]);
//        currentTime.setText(now);

        mCDPYuYue = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                mTVYuYueStartTime.setText(time);
            }
        }, now, future); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        mCDPYuYue.showSpecificTime(true); // 显示时和分
        mCDPYuYue.setIsLoop(true); // 允许循环滚动

        mCDPChangtu = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                mTVChangTuStartTime.setText(time);
            }
        }, now, future);
        mCDPChangtu.showSpecificTime(true);
        mCDPChangtu.setIsLoop(true);

        mCDPOrder = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                mTVStartTime.setText(time);
            }
        }, now, future);
        mCDPOrder.showSpecificTime(true);
        mCDPOrder.setIsLoop(true);
    }

    // 设置地图是否允许操作
    private void setMapAllGestures(boolean isAllow) {
        mBaiduMap.getUiSettings().setAllGesturesEnabled(isAllow);
        if (isAllow) {
            setPadding(180);
            addView(mMapView);
        } else {
            setPadding(0);
            mMapView.removeView(mTVPadding);
        }
    }

    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            locationService.stop();// 停止定位

            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }

            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
//                showToast("gps定位成功");
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
//                showToast("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
//                showToast("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                showToast("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                return;
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                showToast("网络不通导致定位失败，请检查网络是否通畅");
                return;
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                showToast("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                return;
            }

            SPUtils.put(mApp, "loccity", location.getCity());
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            locData = new MyLocationData.Builder()
//                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
//                    .direction(mCurrentDirection)
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);


            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude()); // 向上偏移
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll);
            if (isFirstLoc) {
                isFirstLoc = false;
                builder.zoom(12.8f);
            }

            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

//            if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
//                Poi poi = location.getPoiList().get(1);
//                mStartLocName = poi.getName();
//            } else {
//                mStartLocName = "";
//            }
//            setStartLocText(mStartLocName);

//            MarkerOptions ooC = new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).perspective(false).icon(mMarker);
//            mBaiduMap.addOverlay(ooC);
            //showToast("location参数："+String.valueOf(location.getLongitude())+","+String.valueOf(location.getLatitude())+","+location.getProvince()+","+location.getCity()+","+location.getDistrict());
            mEngine.location(String.valueOf(location.getLongitude()), String.valueOf(location.getLatitude()), location.getProvince(), location.getCity(), location.getDistrict()).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String str = response.body().string();
                        JSONObject jo = new JSONObject(str);
                        int status = jo.getInt("status");
                        String msg = jo.getString("msg");
                        String fid = jo.getString("fid");
                        SPUtils.put(mApp, "fid", fid);
                        JSONArray ja = jo.getJSONArray("result");


//                        mDriverList.clear();
//                        for (int i = 0; i < ja.length(); i++) {
//                            mDriverList.add(GsonUtil.jsonToDriverBean(ja.getJSONObject(i).getString("ldata")));
//                        }

                        if (status == 200) {
                            showToast("定位成功");
                        } else if (status == 104) {
                            showToast("当前地区未开通服务");
                        } else if (status == 101) {
                            showToast("未找到匹配的省份");
                        } else if (status == 102) {
                            showToast("未找到匹配的城市");
                        } else if (status == 103) {
                            showToast("未找到匹配的县区");
                        } else {
                            showToast("定位异常");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                }
            });

//            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
//                StringBuffer sb = new StringBuffer(256);
//                sb.append("time : ");
//                /**
//                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
//                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
//                 */
//                sb.append(location.getTime());
//                sb.append("\nlocType : ");// 定位类型
//                sb.append(location.getLocType());
//                sb.append("\nlocType description : ");// *****对应的定位类型说明*****
//                sb.append(location.getLocTypeDescription());
//                sb.append("\nCoorType : ");// 坐标类型
//                sb.append(location.getCoorType());
//                sb.append("\nlatitude : ");// 纬度
//                sb.append(location.getLatitude());
//                sb.append("\nlontitude : ");// 经度
//                sb.append(location.getLongitude());
//                sb.append("\nradius : ");// 半径
//                sb.append(location.getRadius());
//                sb.append("\nCountryCode : ");// 国家码
//                sb.append(location.getCountryCode());
//                sb.append("\nCountry : ");// 国家名称
//                sb.append(location.getCountry());
//                sb.append("\nProvince : ");// 省
//                sb.append(location.getProvince());
//                sb.append("\ncitycode : ");// 城市编码
//                sb.append(location.getCityCode());
//                sb.append("\ncity : ");// 城市
//                sb.append(location.getCity());
//                sb.append("\nDistrict : ");// 区
//                sb.append(location.getDistrict());
//                sb.append("\nStreet : ");// 街道
//                sb.append(location.getStreet());
//                sb.append("\naddr : ");// 地址信息
//                sb.append(location.getAddrStr());
//                sb.append("\nUserIndoorState: ");// *****返回用户室内外判断结果*****
//                sb.append(location.getUserIndoorState());
//                sb.append("\nDirection(not all devices have value): ");
//                sb.append(location.getDirection());// 方向
//                sb.append("\nlocationdescribe: ");
//                sb.append(location.getLocationDescribe());// 位置语义化信息
//                sb.append("\nPoi: ");// POI信息
//                if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
//                    for (int i = 0; i < location.getPoiList().size(); i++) {
//                        Poi poi = (Poi) location.getPoiList().get(i);
//                        sb.append(poi.getName() + ";");
//                    }
//                }
//                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
//                    sb.append("\nspeed : ");
//                    sb.append(location.getSpeed());// 速度 单位：km/h
//                    sb.append("\nsatellite : ");
//                    sb.append(location.getSatelliteNumber());// 卫星数目
//                    sb.append("\nheight : ");
//                    sb.append(location.getAltitude());// 海拔高度 单位：米
//                    sb.append("\ngps status : ");
//                    sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
//                    sb.append("\ndescribe : ");
//                    sb.append("gps定位成功");
//                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
//                    // 运营商信息
//                    if (location.hasAltitude()) {// *****如果有海拔高度*****
//                        sb.append("\nheight : ");
//                        sb.append(location.getAltitude());// 单位：米
//                    }
//                    sb.append("\noperationers : ");// 运营商信息
//                    sb.append(location.getOperators());
//                    sb.append("\ndescribe : ");
//                    sb.append("网络定位成功");
//                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
//                    sb.append("\ndescribe : ");
//                    sb.append("离线定位成功，离线定位结果也是有效的");
//                } else if (location.getLocType() == BDLocation.TypeServerError) {
//                    sb.append("\ndescribe : ");
//                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
//                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
//                    sb.append("\ndescribe : ");
//                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
//                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
//                    sb.append("\ndescribe : ");
//                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
//                }
//                logMsg(sb.toString());
//            }
        }
    };

    // 设置下单方式tab
    private void setWayTab(int index) {
        if (index == 0) {
            mTVDaily.setBackgroundResource(R.drawable.bg_white_blue_bigradius);
            mTVDaily.setTextColor(getResources().getColor(R.color.colorPrimary));
            mTVYuYue.setBackgroundResource(0);
            mTVYuYue.setTextColor(getResources().getColor(R.color.black));
            mTVChangTu.setBackgroundResource(0);
            mTVChangTu.setTextColor(getResources().getColor(R.color.black));
        } else if (index == 1) {
            mTVYuYue.setBackgroundResource(R.drawable.bg_white_blue_bigradius);
            mTVYuYue.setTextColor(getResources().getColor(R.color.colorPrimary));
            mTVChangTu.setBackgroundResource(0);
            mTVChangTu.setTextColor(getResources().getColor(R.color.black));
            mTVDaily.setBackgroundResource(0);
            mTVDaily.setTextColor(getResources().getColor(R.color.black));
        } else if (index == 2) {
            mTVChangTu.setBackgroundResource(R.drawable.bg_white_blue_bigradius);
            mTVChangTu.setTextColor(getResources().getColor(R.color.colorPrimary));
            mTVYuYue.setBackgroundResource(0);
            mTVYuYue.setTextColor(getResources().getColor(R.color.black));
            mTVDaily.setBackgroundResource(0);
            mTVDaily.setTextColor(getResources().getColor(R.color.black));
        }
        mVPMain.setCurrentItem(index);
    }

    // 修改页面出发地
    private void setStartLocText(String locName, LatLng latLng) {
        mTVDailyStartLoc.setText(locName);
        mTVYuYueStartLoc.setText(locName);
        mTVChangTuStartLoc.setText(locName);
        mTVStartLoc.setText(locName);
        if (latLng != null) {
            mStartLon = latLng.longitude;
            mStartLat = latLng.latitude;
        } else {
            mStartLon = 0.0;
            mStartLat = 0.0;
        }
    }

    // 选择司机数量弹窗
    private void showDriverCountPopWin(View v) {
        mDriverCountPopWin = new DriverCountPopWin(this, this);
        Util.backgroundAlpha(this, 0.5f);
        mDriverCountPopWin.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    // 设置地图底部渐变背景
    private void setPadding(int padding) {
        paddingBottom = Util.dip2px(mApp, padding);
        mBaiduMap.setViewPadding(0, 0, 0, paddingBottom);
    }

    TextView mTVPadding;

    private void addView(TextureMapView mapView) {
        mTVPadding = new TextView(this);
        mTVPadding.setBackgroundResource(R.drawable.gradient_white);

        MapViewLayoutParams.Builder builder = new MapViewLayoutParams.Builder();
        builder.layoutMode(MapViewLayoutParams.ELayoutMode.absoluteMode);
        builder.width(mapView.getWidth());
        builder.height(paddingBottom);
        builder.point(new Point(0, mapView.getHeight()));
        builder.align(MapViewLayoutParams.ALIGN_LEFT, MapViewLayoutParams.ALIGN_BOTTOM);

        mapView.addView(mTVPadding, builder.build());
    }

    // 重置下单
    private void resetOrder() {
        mTVMPerson.setText("");
        mTVEndLoc.setText("");
        mEndLon = 0;
        mEndLat = 0;
        mTVRemark.setText("");
//        if (!mDriverCount.equals("1")) {
//            mDriverCount = "1";
//            mTVDCount.setText(mDriverCount + "名司机");
//            mTVEndLoc.setVisibility(View.VISIBLE);
//        }
        mTVStartTime.setText("");
        mTVGuJia.setText("");
        mLLGuJia.setVisibility(View.GONE);
        mIVPosition.setVisibility(View.VISIBLE);
        mLLWay.setVisibility(View.VISIBLE);
        mVPMain.setVisibility(View.VISIBLE);

        mRLAcceptOrder.setVisibility(View.GONE);
    }

    BaiduMap.OnMapStatusChangeListener onMapStatusChangeListener = new BaiduMap.OnMapStatusChangeListener() {
        /**
         * 手势操作地图，设置地图状态等操作导致地图状态开始改变。
         * @param status 地图状态改变开始时的地图状态
         */
        public void onMapStatusChangeStart(MapStatus status) {
        }

        /** 因某种操作导致地图状态开始改变。
         * @param status 地图状态改变开始时的地图状态
         * @param reason 表示地图状态改变的原因，取值有：
         * 1：用户手势触发导致的地图状态改变,比如双击、拖拽、滑动底图
         * 2：SDK导致的地图状态改变, 比如点击缩放控件、指南针图标
         * 3：开发者调用,导致的地图状态改变
         */
        public void onMapStatusChangeStart(MapStatus status, int reason) {
            mRLTip.setVisibility(View.GONE);
        }

        /**
         * 地图状态变化中
         * @param status 当前地图状态
         */
        public void onMapStatusChange(MapStatus status) {
        }

        /**
         * 地图状态改变结束
         * @param status 地图状态改变结束后的地图状态
         */
        public void onMapStatusChangeFinish(MapStatus status) {
            if (isPushOrder) { // 是否是下单中操作地图
                return;
            }
            mRLTip.setVisibility(View.VISIBLE);
//            mPoiSearch.searchNearby(new PoiNearbySearchOption()
//                    .keyword("科技创业园")
//                    .sortType(PoiSortType.distance_from_near_to_far)
//                    .location(new LatLng(mStartLat, mStartLon))
//                    .radius(500)
//                    .pageNum(10));

//            mSearch.geocode(new GeoCodeOption()
//                    .city("安庆")
//                    .address("安庆"));

            setStartLocText("正在获取当前位置", null);
            mGeoSearch.reverseGeoCode(new ReverseGeoCodeOption().location(status.target));
        }
    };

    OnGetGeoCoderResultListener geoCoderResultListener = new OnGetGeoCoderResultListener() {


        public void onGetGeoCodeResult(GeoCodeResult result) {

            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有检索到结果
            }

            //获取地理编码结果
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
            mBaiduMap.clear();
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
                setStartLocText("未检测到周边信息，请重新定位", null);
                return;
            } else {
                mCurGeoCodeResult = result;
            }

            //获取反向地理编码结果
            mCurrentPoiList = result.getPoiList();
            if (mCurrentPoiList.size() > 0) {
                setStartLocText(mCurrentPoiList.get(0).name, mCurrentPoiList.get(0).location);
            }
//            else if (mCurrentPoiList.size() == 1) {
//                setStartLocText(mCurrentPoiList.get(0).name,  mCurrentPoiList.get(0).location);
//            }
            else {
                setStartLocText(result.getAddress(), result.getLocation());
            }

            if (mEndLon != 0) {
                PlanNode stNode = PlanNode.withLocation(new LatLng(mStartLat, mStartLon));
                PlanNode enNode = PlanNode.withLocation(new LatLng(mEndLat, mEndLon));
                mRoutePlanSearch.drivingSearch((new DrivingRoutePlanOption())
                        .from(stNode)
                        .to(enNode));
                mTVGuJia.setText("");
            }

            String province = result.getAddressDetail().province;
            String city = result.getAddressDetail().city;
            String district = result.getAddressDetail().district;

            mEngine.moveLocation(String.valueOf(result.getLocation().longitude),
                    String.valueOf(result.getLocation().latitude), province, city, district).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {

                        String str = response.body().string();

                        LogsUtil.normal("初始数据" + str);
                        str = str.replace("null", "[\n" +
                                "    {\n" +
                                "      \"distance\": 0,\n" +
                                "      \"ldata\": {\n" +
                                "        \"sj_id\": 0,\n" +
                                "        \"number\": \"0\",\n" +
                                "        \"mobile\": \"0\",\n" +
                                "        \"sb_long\": \"0\",\n" +
                                "        \"sb_lat\": \"0\",\n" +
                                "        \"name\": \"\",\n" +
                                "        \"head_pic\": \"\",\n" +
                                "        \"nickname\": \"\"\n" +
                                "      }\n" +
                                "    }\n" +
                                "  ]");
                        LogsUtil.normal("获取附近司机成功后台返回--" + str);

                        JSONObject jo = new JSONObject(str);
                        int status = jo.getInt("status");
                        String msg = jo.getString("msg");
                        String fid = jo.getString("fid");
                        JSONArray ja = jo.getJSONArray("result");
                        mDriverList.clear();
                        DriverModel modelFrist = GsonUtil.jsonToDriverBean(ja.getJSONObject(0).getString("ldata"));

                        //ja.getJSONObject(0).getInt("distance") == 0 &&
                        if ("0".equals(modelFrist.getSb_lat())) {
                            mTVTipDistance.setText("0.0\n公里");
                            mTVTipDistance.setVisibility(View.GONE);
                            mTVTipMsg.setText("附近暂无空闲司机");
                            return;
                        } else {
                            mTVTipDistance.setVisibility(View.VISIBLE);
                            mTVTipMsg.setText("从这里出发\n(附近有" + ja.length() + "名司机)");
                        }

                        for (int i = 0; i < ja.length(); i++) {
                            DriverModel model = GsonUtil.jsonToDriverBean(ja.getJSONObject(i).getString("ldata"));
                            mDriverList.add(model);
                            if (i == 0) {
                                mTVTipDistance.setText(ja.getJSONObject(i).getInt("distance") / 1000 + "\n公里");
                            }

                            LatLng latLng = new LatLng(Double.valueOf(model.getSb_lat()).doubleValue(), Double.valueOf(model.getSb_long()).doubleValue());
                            View view = LayoutInflater.from(mApp).inflate(R.layout.view_descriptor_driver, null); // 司机渲染

                            Glide.with(mApp).load(Constants.BASE_URL + model.getHead_pic())
//                                    .placeholder(R.drawable.loading_blank)
//                                    .error(R.drawable.loading_blank)
//                                    .fallback(R.drawable.loading_blank)
                                    .into((ImageView) view.findViewById(R.id.view_iv_head));
                            ((TextView) view.findViewById(R.id.view_tv_nickname)).setText(model.getName());

                            MarkerOptions mo = new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromView(view)).zIndex(9);
                            mBaiduMap.addOverlay(mo);
                        }

                        if (status == 200) {
                        } else if (status == 105) {
                            showToast("暂不提供跨地区服务");
                        } else if (status == 104) {
                            showToast("当前地区未开通服务");
                        } else if (status == 101) {
                            showToast("未找到匹配的省份");
                        } else if (status == 102) {
                            showToast("未找到匹配的城市");
                        } else if (status == 103) {
                            showToast("未找到匹配的县区");
                        } else {
                            showToast("定位异常");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        LogsUtil.error("获取附近司机信息" + e);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        LogsUtil.error("获取附近司机信息" + e);

                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                }
            });
        }
    };

    private void setRefreshDriver(ReverseGeoCodeResult result) {

        String province = result.getAddressDetail().province;
        String city = result.getAddressDetail().city;
        String district = result.getAddressDetail().district;

        mEngine.moveLocation(String.valueOf(result.getLocation().longitude),
                String.valueOf(result.getLocation().latitude), province, city, district).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {

                    String str = response.body().string();

                    str = str.replace("null", "[\n" +
                            "    {\n" +
                            "      \"distance\": 0,\n" +
                            "      \"ldata\": {\n" +
                            "        \"sj_id\": 0,\n" +
                            "        \"number\": \"0\",\n" +
                            "        \"mobile\": \"0\",\n" +
                            "        \"sb_long\": \"0\",\n" +
                            "        \"sb_lat\": \"0\",\n" +
                            "        \"name\": \"\",\n" +
                            "        \"head_pic\": \"\",\n" +
                            "        \"nickname\": \"\"\n" +
                            "      }\n" +
                            "    }\n" +
                            "  ]");
                    LogsUtil.normal("response--" + str);

                    JSONObject jo = new JSONObject(str);
                    int status = jo.getInt("status");
                    String msg = jo.getString("msg");
                    String fid = jo.getString("fid");
                    JSONArray ja = jo.getJSONArray("result");
                    mDriverList.clear();

                    LogsUtil.normal("大小--" + ja.length() + "status" + status);

                    if (ja.getJSONObject(0).getInt("distance") == 0) {
                        mTVTipDistance.setText("0.0\n公里");
                        mTVTipDistance.setVisibility(View.GONE);
                        mTVTipMsg.setText("附近暂无空闲司机");
                        return;
                    } else {
                        mTVTipDistance.setVisibility(View.VISIBLE);
                        mTVTipMsg.setText("从这里出发\n(附近有" + ja.length() + "名司机)");
                    }

                    for (int i = 0; i < ja.length(); i++) {
                        DriverModel model = GsonUtil.jsonToDriverBean(ja.getJSONObject(i).getString("ldata"));
                        mDriverList.add(model);
                        if (i == 0) {
                            mTVTipDistance.setText(ja.getJSONObject(i).getInt("distance") / 1000 + "\n公里");
                        }

                        LatLng latLng = new LatLng(Double.valueOf(model.getSb_lat()).doubleValue(), Double.valueOf(model.getSb_long()).doubleValue());
                        View view = LayoutInflater.from(mApp).inflate(R.layout.view_descriptor_driver, null); // 司机渲染

                        Glide.with(mApp).load(Constants.BASE_URL + model.getHead_pic())
//                                    .placeholder(R.drawable.loading_blank)
//                                    .error(R.drawable.loading_blank)
//                                    .fallback(R.drawable.loading_blank)
                                .into((ImageView) view.findViewById(R.id.view_iv_head));

//                        ((TextView) view.findViewById(R.id.view_tv_nickname)).setText(model.getName());
                        ((TextView) view.findViewById(R.id.view_tv_nickname)).setText(model.getSj_id());

                        MarkerOptions mo = new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromView(view)).zIndex(9);
                        mBaiduMap.addOverlay(mo);
                    }

                    if (status == 200) {
                    } else if (status == 105) {
                        showToast("暂不提供跨地区服务");
                    } else if (status == 104) {
                        showToast("当前地区未开通服务");
                    } else if (status == 101) {
                        showToast("未找到匹配的省份");
                    } else if (status == 102) {
                        showToast("未找到匹配的城市");
                    } else if (status == 103) {
                        showToast("未找到匹配的县区");
                    } else {
                        showToast("定位异常");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    LogsUtil.error("获取附近司机信息" + e);
                } catch (JSONException e) {
                    e.printStackTrace();
                    LogsUtil.error("获取附近司机信息" + e);

                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });


    }

    OnGetRoutePlanResultListener routePlanResultListener = new OnGetRoutePlanResultListener() {

        @Override
        public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

        }

        @Override
        public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

        }

        @Override
        public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

        }

        public void onGetDrivingRouteResult(DrivingRouteResult result) {

            //获取驾车线路规划结果
            if (result.getRouteLines().size() > 0) {
                int distance = result.getRouteLines().get(0).getDistance();
                final double diskil = distance / 1000.0;
                mEngine.getCharge(userModel.getUser_id()).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            String str = response.body().string();
                            JSONObject jo = new JSONObject(str);
                            int status = jo.getInt("status");
                            String msg = jo.getString("msg");
                            if (status == 200) {
                                double sprice = jo.getJSONObject("result").getDouble("sprice");
                                double uprice = jo.getJSONObject("result").getDouble("uprice");
                                double kilometres = jo.getJSONObject("result").getDouble("kilometres");
                                if (diskil > kilometres) {
                                    int price = (new Double((diskil - kilometres) * uprice + sprice)).intValue();
                                    mTVGuJia.setText("约" + String.valueOf(price) + "元");
                                } else {
                                    mTVGuJia.setText("约" + String.valueOf(sprice) + "元");
                                }

                            } else {
                                showToast("获取计价列表异常");
                                mTVGuJia.setText("无预估价");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        mTVGuJia.setText("无预估价");
                    }
                });
            } else {
                mTVGuJia.setText("无预估价");
            }
        }

        @Override
        public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

        }

        @Override
        public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

        }
    };

}
